package cn.camel.algorithm.graph;
import java.util.*;

/**
 * @author: Camel
 * @description: 邻接表实现图
 * @date: 2025/10/20 12:37
 */
public class GraphList {
    private Map<Integer, List<Integer>> adjList;
    private int numVertices;

    public GraphList(int numVertices) {
        this.numVertices = numVertices;
        adjList = new HashMap<>();
        for (int i = 0; i < numVertices; i++) {
            adjList.put(i, new LinkedList<>());
        }
    }

    // 添加边（无向图）
    public void addEdge(int src, int dest) {
        adjList.get(src).add(dest);
        adjList.get(dest).add(src); // 有向图时注释此行
    }

    // 打印邻接表
    public void printList() {
        for (int i = 0; i < numVertices; i++) {
            System.out.print(i + ": ");
            for (Integer neighbor : adjList.get(i)) {
                System.out.print(neighbor + " ");
            }
            System.out.println();
        }
    }

    // 邻接表版DFS（递归）
    public void dfs(int start) {
        boolean[] visited = new boolean[numVertices];
        dfsRecursive(start, visited);
    }

    private void dfsRecursive(int vertex, boolean[] visited) {
        visited[vertex] = true;
        System.out.print(vertex + " ");

        for (int neighbor : adjList.get(vertex)) {
            if (!visited[neighbor]) {
                dfsRecursive(neighbor, visited);
            }
        }
    }

    // 邻接表版BFS
    public void bfs(int start) {
        boolean[] visited = new boolean[numVertices];
        Queue<Integer> queue = new LinkedList<>();

        visited[start] = true;
        queue.add(start);

        while (!queue.isEmpty()) {
            int vertex = queue.poll();
            System.out.print(vertex + " ");

            for (int neighbor : adjList.get(vertex)) {
                if (!visited[neighbor]) {
                    visited[neighbor] = true;
                    queue.add(neighbor);
                }
            }
        }
    }



    public static void main(String[] args) {
        // 创建图（5个顶点）
        GraphList graph = new GraphList(5);

        // 添加边
        graph.addEdge(0, 1);
        graph.addEdge(0, 4);
        graph.addEdge(1, 2);
        graph.addEdge(1, 3);
        graph.addEdge(1, 4);
        graph.addEdge(3, 4);

        System.out.println("邻接表结构:");
        graph.printList();

        System.out.println("\nDFS遍历:");
        graph.dfs(0);

        System.out.println("\n\nBFS遍历:");
        graph.bfs(0);
    }

}
